#include "AAAAttrbute.h"
#include <string.h>
#include <iostream>

AAAAttrbute::AAAAttrbute(const AAAAttrbute &other)
{
    _type = other.type();
    _length = other.length();
    _val = other.val();
    _pbuf = nullptr;
}

EAttrType AAAAttrbute::type() const
{
    return _type;
}

void AAAAttrbute::setType(const EAttrType type)
{
    _type = type;
}

uint8_t AAAAttrbute::length() const
{
    return _length;
}

std::string AAAAttrbute::val() const
{
    return _val;
}

void AAAAttrbute::setVal(const void *data, uint8_t len)
{
    _val.append( (const char*)data, len );
    _length += _val.length();
}

bool AAAAttrbute::pack( uint8_t *&data, uint8_t &dataLen)
{
    if ( _type == EAttrType::NONE_TYPE || _val == "" )
    {
        return false;
    }
    //申请内存,申请新内存的时候原内存会被释放掉
    std::shared_ptr<uint8_t> tmp( new uint8_t[_length] );
   _pbuf = tmp;
    //方便填充数据
    struct SAttrPack* pattr = (struct SAttrPack*)_pbuf.get();
    //填充数据
    pattr->typePlace = _type;
    pattr->lengthPlace = _length;
    ::memcpy( &pattr->lengthPlace+sizeof(_length), _val.data(), _val.length() );
    data = _pbuf.get();
    dataLen = _length;
    return true;
}

void AAAAttrbute::print()
{
    std::cout << "type: " << (uint32_t)_type << std::endl;
    std::cout << "len: " << (uint32_t)_length << std::endl;
    printf( "data: " );
    for( uint16_t i = 0; i < _length ; ++i )
    {
        printf( "%02x ", *((uint8_t*)_pbuf.get()+i) );
    }
    printf("\n");
}
